//
//  AnalogClock.m
//  AnalogClock
//
//  Created by Le Thanh Hai on 10/7/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "AnalogClock.h"
#import <QuartzCore/QuartzCore.h>

#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
@implementation AnalogClock

- (void) drawLineForContext:(const CGContextRef&)context Width:(float)_width angle:(double)_angle length:(double)radius
{
	CGPoint c = CGPointMake(self.frame.size.width/2.0, self.frame.size.height/2.0);
	
	CGContextSetLineWidth(context, _width);
	CGContextMoveToPoint(context, self.center.x, self.center.y);
	CGPoint addLines[] =
	{
        //		CGPointMake(self.frame.size.width/2.0, self.frame.size.height/2.0),
		CGPointMake(0.2*(-radius*cos(_angle)) +c.x, 0.2*(-radius*sin(_angle)) +c.y),
		CGPointMake(radius*cos(_angle) +c.x, radius*sin(_angle) +c.y),
	};
	
	CGContextAddLines(context, addLines, sizeof(addLines)/sizeof(addLines[0]));
	CGContextStrokePath(context);
}

- (id)initWithFrame:(CGRect)frame andR:(float)R G:(float)G B:(float)B
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        r = R;
        g = G;
        b = B;
    }
    return self;
}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *now = [NSDate date];
    int h = [[cal components:NSHourCalendarUnit fromDate:now] hour];
    int m = [[cal components:NSMinuteCalendarUnit fromDate:now] minute];
    int s = [[cal components:NSSecondCalendarUnit fromDate:now] second];
    [cal release];
    BOOL isAM = h < 12;
    double hAlpha = DEGREES_TO_RADIANS((isAM?h:h-12)*30 + (30*m/60)-90);
    double mAlpha = DEGREES_TO_RADIANS(m*6 - 90);
    double sAlpha = DEGREES_TO_RADIANS(s*6 - 90);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, r, g, b, 1.0f);
    [self drawLineForContext:context Width:4.0f angle:hAlpha length:self.frame.size.width/2.0 - 36];
    [self drawLineForContext:context Width:5.0f angle:mAlpha length:self.frame.size.width/2.0 - 26];
    CGContextSetRGBStrokeColor(context, 1.0f, 0.0f, 0.0f, 1.0f);
    [self drawLineForContext:context Width:2.0 angle:sAlpha length:self.frame.size.width/2.0 - 20]; 
    
    // Draw a circle (filled)
    CGContextSetRGBFillColor(context, 1.0, 0, 0, 1);    
    CGContextFillEllipseInRect(context, CGRectMake(self.frame.size.width/2.0 - 5, self.frame.size.height/2.0 - 5, 10, 10));
}


-(void)update
{
	[self setNeedsDisplay];
}

-(void)startClockUpdates
{
	[self update];
	timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(update) userInfo:nil repeats:YES];
}
-(void)stopClockUpdates
{
	[timer invalidate], timer = nil;
}

- (void)dealloc
{
    [self stopClockUpdates];
    [super dealloc];
}

@end
